﻿using System;
using Microsoft.Extensions.Logging;
using SqlSugar;

namespace JIESHINet.Repository.UnitOfWorks;

/// <summary>
/// 负责事务处理和资源释放的工作单元
/// </summary>
public class UnitOfWork : IDisposable
{
    /// <summary>
    /// 日志记录器。
    /// </summary>
    public ILogger Logger { get; set; }
    /// <summary>
    ///  SQLSugar 数据库客户端。
    /// </summary>
    public ISqlSugarClient Db { get; internal set; }
    /// <summary>
    /// 租户信息
    /// </summary>
    public ITenant Tenant { get; internal set; }
    /// <summary>
    /// 是否处于事务中。
    /// </summary>
    public bool IsTran { get; internal set; }
    /// <summary>
    /// 事务是否已提交。
    /// </summary>
    public bool IsCommit { get; internal set; }
    /// <summary>
    /// 事务是否已关闭
    /// </summary>
    public bool IsClose { get; internal set; }

    /// <summary>
    /// 释放资源，根据事务状态进行提交或回滚。
    /// </summary>
    public void Dispose()
    {
        if (this.IsTran && !this.IsCommit)
        {
            Logger.LogDebug("UnitOfWork RollbackTran");
            this.Tenant.RollbackTran();
        }

        if (this.Db.Ado.Transaction != null || this.IsClose)
            return;
        this.Db.Close();
    }

    /// <summary>
    /// 提交事务，根据事务状态进行提交或回滚。
    /// </summary>
    /// <returns></returns>
    public bool Commit()
    {
        if (this.IsTran && !this.IsCommit)
        {
            Logger.LogDebug("UnitOfWork CommitTran");
            this.Tenant.CommitTran();
            this.IsCommit = true;
        }

        if (this.Db.Ado.Transaction == null && !this.IsClose)
        {
            this.Db.Close();
            this.IsClose = true;
        }

        return this.IsCommit;
    }
}